<template>
  <div class="app-container">
    <!-- 查询区域 -->
    <el-card class="search-card">
      <el-form :model="queryParams">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="水厂选择">
              <el-select v-model="queryParams.factoryId" placeholder="请选择水厂" clearable style="width: 100%">
                <el-option label="全部水厂" value="" />
                <el-option v-for="item in factoryOptions" :key="item.dictValue" :label="item.dictLabel"
                  :value="item.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" style="text-align: left;">
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 数据概览卡片 -->
    <el-row :gutter="20" class="stats-cards">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon size="24">
                <Box />
              </el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ warehouseStock }}</div>
              <div class="stat-label">仓库药剂库存</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="color: #67C23A;">
              <el-icon size="24">
                <TrendCharts />
              </el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ consumptionData.length }}</div>
              <div class="stat-label">药耗类型数量</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="color: #E6A23C;">
              <el-icon size="24">
                <Warning />
              </el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ warningCount }}</div>
              <div class="stat-label">库存预警数量</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" style="color: #409EFF;">
              <el-icon size="24">
                <DataAnalysis />
              </el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ predictionData.length }}</div>
              <div class="stat-label">预测药剂数量</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表展示区域 -->
    <el-row :gutter="20" class="chart-area">
      <!-- 药耗曲线图 -->
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <el-select v-model="curveParam" size="small" style="width: 200px">
                  <el-option label="按日统计所有时间消耗" :value="1" />
                  <el-option label="按日统计最近7天消耗" :value="2" />
                  <el-option label="按月统计最近6个月消耗" :value="3" />
                  <el-option label="按年统计最近5年消耗" :value="4" />
                </el-select>
          </template>
          <ChartComponent :option="curveChartOption" :style="{ height: '350px' }" />
        </el-card>
      </el-col>

      <!-- 药耗占比图 -->
      <el-col :span="12">
        <el-card class="chart-card">
          <ChartComponent :option="proportionChartOption" :style="{ height: '396px' }" />
        </el-card>
      </el-col>

      <!-- 库存阈值比 -->
      <el-col :span="12">
        <el-card class="chart-card">
          <ChartComponent :option="thresholdChartOption" :style="{ height: '350px' }" />
        </el-card>
      </el-col>

      <!-- 智能预测 -->
      <el-col :span="12">
        <el-card class="chart-card">
          <ChartComponent :option="predictionChartOption" :style="{ height: '350px' }" />
        </el-card>
      </el-col>
    </el-row>

    <!-- 数据表格区域 -->
    <el-card class="table-card">
      <el-tabs v-model="activeTab">
        <!-- 药耗占比数据 -->
        <el-tab-pane label="药耗占比" name="proportion">
          <el-table :data="consumptionData" border v-loading="loading">
            <el-table-column prop="name" label="药剂类型" align="center" />
            <el-table-column prop="total_quantity" label="消耗量" align="center" />
            <el-table-column prop="percentage" label="占比" align="center">
              <template #default="{ row }">
                {{ (row.percentage * 100).toFixed(2) }}%
              </template>
            </el-table-column>
            <el-table-column prop="record_count" label="出库次数" align="center" />
          </el-table>
        </el-tab-pane>

        <!-- 库存阈值数据 -->
        <el-tab-pane label="库存阈值" name="threshold">
          <el-table :data="thresholdData" border v-loading="loading">
            <el-table-column prop="reagentName" label="药剂名称" align="center" />
            <el-table-column prop="currentStock" label="当前库存" align="center" />
            <el-table-column prop="initialStock" label="初始库存" align="center" />
            <el-table-column prop="inventoryWarningValue" label="预警值" align="center" />
            <el-table-column prop="stockWarningPercentage" label="预警百分比" align="center">
              <template #default="{ row }">
                  {{ row.stockWarningPercentage }}%
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 智能预测数据 -->
        <el-tab-pane label="智能预测" name="prediction">
          <el-table :data="predictionData" border v-loading="loading">
            <el-table-column prop="drugName" label="药品名称" align="center" />
            <el-table-column prop="avgMonthlyConsumption" label="月均消耗量" align="center" />
            <el-table-column prop="forecast3Month" label="3个月预测用量" align="center" />
            <el-table-column prop="safetyStock" label="安全库存" align="center" />
            <el-table-column label="建议采购量" align="center">
              <template #default="{ row }">
                  {{ Math.max(0, row.forecast3Month - row.safetyStock).toFixed(0) }}
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Box, TrendCharts, Warning, DataAnalysis } from '@element-plus/icons-vue'
import ChartComponent from '@/components/ECharts'

// API导入
import {
  getFactoryList,
  getWarehousePharmaceuticalStock,
  getMedicineConsumptionProportion,
  getStockThresholdRatio,
  getMedicineConsumptionCurve,
  getIntelligentPrediction
} from '@/api/prod_operate/prod_run/drug_manage/analysis'

const loading = ref(false)

// 查询参数
const queryParams = reactive({
  factoryId: '',
  timeRange: '',
  chartType: ''
})

// 数据状态
const factoryOptions = ref([])
const warehouseStock = ref(0)
const consumptionData = ref([])
const thresholdData = ref([])
const curveData = ref({})
const predictionData = ref([])
const warningCount = ref(0)
const activeTab = ref('proportion')
const curveParam = ref(1)

// 计算属性 - 图表配置
const curveChartOption = computed(() => {
  return {
    title: {
      text: '药耗趋势分析',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      formatter: function (params) {
        let result = params[0].axisValue + '<br/>'
        params.forEach(item => {
          result += `${item.seriesName}: ${item.value}<br/>`
        })
        return result
      }
    },
    legend: {
      data: curveData.value.series?.map(item => item.name) || [],
      bottom: 10
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: curveData.value.dateList || []
    },
    yAxis: {
      type: 'value',
      name: '消耗量'
    },
    series: curveData.value.series?.map(item => ({
      name: item.name,
      type: 'line',
      data: item.data,
      smooth: true
    })) || []
  }
})

const proportionChartOption = computed(() => {
  return {
    title: {
      text: '药耗占比分析',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: consumptionData.value.map(item => item.name)
    },
    series: [
      {
        name: '药耗占比',
        type: 'pie',
        radius: '50%',
        data: consumptionData.value.map(item => ({
          value: item.total_quantity,
          name: item.name
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
})

const thresholdChartOption = computed(() => {
  return {
    title: {
      text: '库存阈值分析',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      name: '库存量'
    },
    yAxis: {
      type: 'category',
      data: thresholdData.value.map(item => item.reagentName)
    },
    series: [
      {
        name: '当前库存',
        type: 'bar',
        data: thresholdData.value.map(item => item.currentStock),
        itemStyle: {
          color: function (params) {
            return params.data > thresholdData.value[params.dataIndex].inventoryWarningValue
              ? '#67C23A' : '#E6A23C'
          }
        }
      },
      {
        name: '预警值',
        type: 'bar',
        data: thresholdData.value.map(item => item.inventoryWarningValue),
        itemStyle: {
          color: '#F56C6C'
        }
      }
    ]
  }
})

const predictionChartOption = computed(() => {
  return {
    title: {
      text: '智能预测分析',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['预测用量', '安全库存'],
      bottom: 10
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: predictionData.value.map(item => item.drugName)
    },
    yAxis: {
      type: 'value',
      name: '数量'
    },
    series: [
      {
        name: '预测用量',
        type: 'bar',
        data: predictionData.value.map(item => item.forecast3Month)
      },
      {
        name: '安全库存',
        type: 'bar',
        data: predictionData.value.map(item => item.safetyStock)
      }
    ]
  }
})

// 获取预警标签类型
const getWarningTagType = (percentage) => {
  if (percentage > 0.8) return 'danger'
  if (percentage > 0.6) return 'warning'
  return 'success'
}

// 初始化数据
onMounted(() => {
  initData()
})

// 初始化所有数据
const initData = async () => {
  try {
    loading.value = true
    await Promise.all([
      fetchFactoryList(),
      fetchWarehouseStock(),
      fetchConsumptionProportion(),
      fetchStockThresholdRatio(),
      fetchMedicineConsumptionCurve(),
      fetchIntelligentPrediction()
    ])
  } catch (error) {
    console.error('初始化数据失败:', error)
    ElMessage.error('初始化数据失败')
  } finally {
    loading.value = false
  }
}

// 获取水厂列表
const fetchFactoryList = async () => {
  try {
    const res = await getFactoryList()
    factoryOptions.value = res.data || []
  } catch (error) {
    console.error('获取水厂列表失败:', error)
    ElMessage.error('获取水厂列表失败')
  }
}

// 获取仓库库存
const fetchWarehouseStock = async () => {
  try {
    const res = await getWarehousePharmaceuticalStock()
    warehouseStock.value = res.data || 0
  } catch (error) {
    console.error('获取仓库库存失败:', error)
    ElMessage.error('获取仓库库存失败')
  }
}

// 获取药耗占比
const fetchConsumptionProportion = async () => {
  try {
    const res = await getMedicineConsumptionProportion()
    consumptionData.value = res.data || []
  } catch (error) {
    console.error('获取药耗占比失败:', error)
    ElMessage.error('获取药耗占比失败')
  }
}

// 获取库存阈值比
const fetchStockThresholdRatio = async () => {
  try {
    const res = await getStockThresholdRatio()
    thresholdData.value = res.data || []
    // 计算预警数量
    warningCount.value = thresholdData.value.filter(item =>
      item.stockWarningPercentage > 0.8
    ).length
  } catch (error) {
    console.error('获取库存阈值比失败:', error)
    ElMessage.error('获取库存阈值比失败')
  }
}

// 获取药耗曲线
const fetchMedicineConsumptionCurve = async () => {
  try {
    const res = await getMedicineConsumptionCurve({ param: curveParam.value })
    curveData.value = res.data || {}
  } catch (error) {
    console.error('获取药耗曲线失败:', error)
    ElMessage.error('获取药耗曲线失败')
  }
}

// 获取智能预测
const fetchIntelligentPrediction = async () => {
  try {
    const res = await getIntelligentPrediction()
    predictionData.value = res.data || []
  } catch (error) {
    console.error('获取智能预测失败:', error)
    ElMessage.error('获取智能预测失败')
  }
}

// 查询处理
const handleQuery = () => {
  initData()
}

// 重置查询
const resetQuery = () => {
  Object.assign(queryParams, {
    factoryId: '',
    timeRange: '',
    chartType: ''
  })
  initData()
}

// 刷新数据
const refreshData = () => {
  initData()
  ElMessage.success('数据刷新成功')
}

// 导出数据
const exportData = () => {
  ElMessage.info('导出功能开发中...')
}

// 监听曲线参数变化
watch(curveParam, (newVal) => {
  fetchMedicineConsumptionCurve()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  margin-bottom: 0;
}

.stat-content {
  display: flex;
  align-items: center;
}

.stat-icon {
  margin-right: 15px;
  color: #409EFF;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.chart-area {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-actions {
  display: flex;
  gap: 10px;
}

.table-card {
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>